<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="oldPassword">
      <el-input v-model="loginForm.oldPassword" type="password" placeholder="输入旧密码">
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="newPassword">
      <el-input v-model="loginForm.newPassword" type="password" placeholder="输入新密码">
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="confirmPassword">
      <el-input
        v-model="loginForm.confirmPassword"
        type="password"
        placeholder="确认新密码"
        show-password
        autocomplete="new-password"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button :icon="CircleClose" round size="large" @click="resetForm()"> 跳过 </el-button>
    <el-button :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)">
      确定修改
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
// import { getTimeState } from "@/utils";
import { Login } from "@/api/interface";
// import { ElNotification } from "element-plus";
// import { loginApi } from "@/api/modules/login";
// import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
// import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import { changePasswordApi } from "@/api/modules/login";
// import md5 from "md5";
// import { testAPI } from "@/api/modules/company";

const router = useRouter();
// const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive<Login.ReqChangePasswordForm>({
  userId: JSON.parse(localStorage.getItem("userInfo") as string).userId,
  oldPassword: "",
  newPassword: "",
  confirmPassword: ""
});
// const getTest = async () => {
//   const { result } = await testAPI({ type: "baidu" });
//   console.log("测试查询结果", result);
// };
// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    // getTest();
    try {
      // 1.执行修改接口
      const { data } = await changePasswordApi({ ...loginForm });
      console.log("修改密码结果", data);
      // userStore.setToken(data.access_token);

      // 2.添加动态路由
      // await initDynamicRouter();
      localStorage.removeItem("token");
      localStorage.removeItem("userInfo");

      // 3.清空 tabs、keepAlive 数据
      tabsStore.setTabs([]);
      keepAliveStore.setKeepAliveName([]);

      // 4.跳转到首页
      console.log("首页地址", HOME_URL);
      router.push(HOME_URL);
      // ElNotification({
      //   title: getTimeState(),
      //   message: "欢迎登录 Geeker-Admin",
      //   type: "success",
      //   duration: 3000
      // });
      // ElNotification({
      //   title: "欢迎登录 🔥🔥🔥",
      //   dangerouslyUseHTMLString: true,
      //   message: "登录成功",
      //   type: "success",
      //   duration: 3000
      // });
    } finally {
      loading.value = false;
    }
  });
};

// resetForm
const resetForm = () => {
  router.push(HOME_URL);
};

onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});

onBeforeUnmount(() => {
  document.onkeydown = null;
});
</script>

<style scoped lang="scss">
@import "../index";
</style>
